package org.common.utils.tool.window;
import javax.swing.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;

/**
 * 重向定System.out,System.err输出至JTextArea中。
 * @author zhouzhibing
 * @date 2025/1/6
 */
public class RedirectSystemPrintln {

    private static PrintStream CONSOLE_OUT;

    private static PrintStream CONSOLE_ERR;

    /**
     * 进行System输出重定向，向textArea中输出
     * @param textArea JTextArea文本域对象
     */
    public static synchronized void redirect(JTextArea textArea) {
        if(CONSOLE_OUT == null)
            CONSOLE_OUT = System.out;

        if(CONSOLE_ERR == null)
            CONSOLE_ERR = System.err;

        OutputStream out = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                updateTextArea(textArea , String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                updateTextArea(textArea , new String(b, off, len));
            }

            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }
        };

        System.setOut(new PrintStream(out, true));
        System.setErr(new PrintStream(out, true));
    }


    /**
     * 向JTextArea追加内容
     * @param textArea JTextArea文本域对象
     * @param text 文本内容
     */
    private static void updateTextArea(final JTextArea textArea , final String text) {
        if (SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeLater(() -> {
                setText(textArea , text);
            });
        } else {
            try {
                SwingUtilities.invokeAndWait(() -> {
                    setText(textArea , text);
                });
            } catch (InterruptedException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private static void setText(final JTextArea textArea , final String text) {
//        CONSOLE_OUT.println(text);
        textArea.append(text);
        textArea.setCaretPosition(textArea.getDocument().getLength());
    }

}
